package com.hz.friends.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.hz.friends.chat.GroupChatActivity;
import com.hz.friends.serverrequest.ALEngineConfig.ALUserGender;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.serverrequest.ALUserEngine;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

public class AddFriendsActivity extends BaseActivity {
	private ListView mlistView;
	private EditText edt_search;
	private FriendAdpter madpter;
	private AQuery aq;
	private final String TAG = "AddFriendsActivity";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_addfriends);
		init();
		initViews();
		initEvents();
	}

	@Override
	protected void init() {
		aq = new AQuery(this);
	}

	@Override
	protected void initViews() {
		ImageButton imbtn_bar_left = (ImageButton) findViewById(R.id.imbtn_bar_left);
		ImageButton imbtn_bar_right = (ImageButton) findViewById(R.id.imbtn_bar_right);
		TextView imbtn_bar_title = (TextView) findViewById(R.id.imbtn_bar_title);
		imbtn_bar_right.setVisibility(View.INVISIBLE);
		imbtn_bar_title.setText("Add Friends");
		imbtn_bar_left.setImageResource(R.drawable.ic_leftback_arrow);
		imbtn_bar_left.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		edt_search = (EditText) findViewById(R.id.edt_search); // 搜索框
		mlistView = (ListView) findViewById(R.id.mlistview); // listview
		madpter = new FriendAdpter();
		mlistView.setAdapter(madpter);
	}

	@Override
	protected void setViews() {

	}

	@Override
	protected void initEvents() {
		edt_search.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) { // 搜索
					String serachtxt = edt_search.getText().toString();
					if (!TextUtils.isEmpty(serachtxt)) { // 搜索
						onSearch(serachtxt);
					} else {
						showSysToast("请输入搜索关键字");
					}
				}
				return false;
			}
		});
	}

	private void onSearch(String text) {
		ArrayList<String> keys = new ArrayList<String>();
		keys.add(text);
		ALUserEngine.defauleEngine().searchUserWithNickname(keys, 20, null,
				new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "searchUserWithNickname avexception:" + avexception + "  object:"
								+ object);
						if (avexception == null) {
							List<AVUser> data = (List<AVUser>) object;
							if (data == null || data.size() == 0)
								showSysToast("没有搜索到用户");
							madpter.setData(data);
							madpter.notifyDataSetChanged();
						} else {
							avexception.printStackTrace();
							showSysToast("搜索错误");
						}
					}
				});
 
	}

	class FriendAdpter extends BaseAdapter {
		private List<AVUser> userlist = new ArrayList<AVUser>();
		private List<AVUser> attenuserlist = new ArrayList<AVUser>();

		@Override
		public int getCount() {
			return userlist.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void setData(List<AVUser> userlist) {
			if(userlist == null)
				return;
			this.userlist = userlist;
			loadFriendAttents();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
		final	ViewHolder holder = convertView == null ? new ViewHolder():(ViewHolder) convertView.getTag();
			if(convertView == null){
				convertView = LayoutInflater.from(AddFriendsActivity.this).inflate(
						R.layout.adpter_friendsearch, null);
//				holder = new ViewHolder();
				holder.imv_heard = (ImageView) convertView.findViewById(R.id.imv_heard);
				holder.txv_name = (TextView) convertView.findViewById(R.id.txv_name);
				holder.btn_attention = (Button) convertView.findViewById(R.id.btn_attention);
				holder.layoutxx = (LinearLayout) convertView.findViewById(R.id.layoutxx);
				holder.txv_signature = (TextView) convertView
						.findViewById(R.id.txv_signature);
				holder.layout_sex = (LinearLayout) convertView
						.findViewById(R.id.layout_sex);
				holder.imv_sex = (ImageView) convertView
						.findViewById(R.id.imv_sex);
				holder.txv_age = (TextView) convertView
						.findViewById(R.id.txv_age);
				convertView.setTag(holder);
			}else{
//				holder = (ViewHolder) convertView.getTag();
			}
			
			
			final AVUser avuser = userlist.get(position);
			String name = avuser.getUsername();
			String nickname = avuser.getString("nickname");
			String heardurl = avuser.getString("headViewURL");
			String signature = avuser.getString("signature");
			Date brithday = avuser.getDate("brithday");
			int gender = avuser.getInt("gender");
			
			final int width = DensityUtil.dip2px(AddFriendsActivity.this, 70);
			// default image
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					AddFriendsActivity.this, crclebitmap, width, 1, "#eeeeee");
			holder.imv_heard.setImageBitmap(crclestrokebitmap);

			aq.ajax(heardurl, Bitmap.class, new AjaxCallback<Bitmap>() {

				@Override
				public void callback(String url, Bitmap bitmap,
						AjaxStatus status) {
					Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
							AddFriendsActivity.this, bitmap, width, 1,
							"#eeeeee");
					holder.imv_heard.setImageBitmap(mbitmap);
				}
			});
			holder.txv_name.setText(nickname);
			holder.txv_signature.setText(signature);
			holder.txv_age.setText(String.valueOf(UtilTools.getAgeByBirthday(brithday))); // 年龄
			
			holder.imv_heard.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Bundle bundle = new Bundle();
					bundle.putInt("isother", 1);
					Intent intent = new Intent(AddFriendsActivity.this,
							UserInfosActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			holder.layoutxx.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(AddFriendsActivity.this,
							GroupChatActivity.class);
					startActivity(intent);
				}
			});
			holder.btn_attention.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					addFriend(avuser, holder.btn_attention);
				}
			});
			
			if (gender == ALUserGender.ALUserGenderOfFemale.get_value()) {// 女性
				holder.layout_sex.setBackgroundResource(R.drawable.shape_bj_icwoman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_woman);
			} else {// 男性
				holder.layout_sex.setBackgroundResource(R.drawable.shape_bj_icman_xml);
				holder.imv_sex.setImageResource(R.drawable.ic_man);
			}
			getAttenState(avuser, holder.btn_attention);
			return convertView;
		}
		
		class ViewHolder {
			ImageView imv_heard; // 
			TextView txv_name;//
			Button btn_attention;
			LinearLayout layoutxx;
			TextView txv_signature; //签名
			LinearLayout layout_sex; //性别布局
			ImageView imv_sex; //性别图标
			TextView txv_age; //年龄
		}


		private void addFriend(AVUser avuser, final Button btn) {
			ALUserEngine.defauleEngine().addFollow(avuser, null,
					new CallBack() {

						@Override
						public void done(Object object, AVException avexception) {
							if (avexception == null) {
								showSysToast("关注成功");
								btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
								btn.setEnabled(false);
							} else {
								showSysToast("关注失败");
								avexception.printStackTrace();
							}
						}
					});
		}

		private void getAttenState(AVUser avuser, final Button btn) {
			for (int i = 0; i < attenuserlist.size(); i++) {
				AVUser user = attenuserlist.get(i);
				if (avuser.getObjectId().equals(user.getObjectId())) {
					btn.setBackgroundResource(R.drawable.shape_nearby_attention2);
					btn.setEnabled(false);
					return;
				}
			}
			btn.setBackgroundResource(R.drawable.shape_nearby_attention);
			btn.setEnabled(true);
		}

		private void loadFriendAttents() {
			ALUserEngine.defauleEngine().isMyFollowee(this.userlist,
					new CallBack() {

						@Override
						public void done(Object object, AVException avexception) {
							MLog.i(TAG, "loadFriendAttents avexception:"
									+ avexception + "  object:" + object);
							if (avexception == null) {
								List<AVUser> userlist = (List<AVUser>) object;
								if (userlist == null || userlist.size() == 0)
									return;
								attenuserlist = userlist;
								FriendAdpter.this.notifyDataSetChanged();
							} else {
								avexception.printStackTrace();
							}
						}
					});
		}

	}
}
